<template>
  <div>
    <div>
      <a-breadcrumb>
        <a-breadcrumb-item>Home</a-breadcrumb-item>
        <a-breadcrumb-item>文章管理</a-breadcrumb-item>
        <a-breadcrumb-item @click="router.push({ name: 'BackendBlogList' })" style="cursor: pointer"
          >文章列表</a-breadcrumb-item
        >
        <a-breadcrumb-item>文章列表</a-breadcrumb-item>
      </a-breadcrumb>
    </div>
    <div style="margin-top: 10px">
      <a-form :model="form" layout="vertical">
        <a-row :gutter="16">
          <a-col :span="24">
            <a-form-item field="title" label="标题" label-col-flex="100px">
              <a-input v-model="form.title" placeholder="请输入文章标题..." />
            </a-form-item>
          </a-col>
        </a-row>
        <a-row :gutter="16">
          <a-form-item field="content" label="内容" label-col-flex="100px">
            <MdEditor v-model="form.content" @onSave="onSaveHandller" />
          </a-form-item>
        </a-row>
      </a-form>
    </div>
  </div>
</template>
<script setup>
import { onMounted, reactive } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { BLOG_CREATE, BLOG_GET, BLOG_UPDATE } from '@/api/blog'
import { Message } from '@arco-design/web-vue'
const form = reactive({
  title: '',
  content: ''
})
const router = useRouter()
const route = useRoute()

// onSave 事件: v value, h渲染后的html
const onSaveHandller = async () => {
  try {
    const id = route.query.id
    if (id) {
      // 执行更新
      const resp = await BLOG_UPDATE(id, form)
      Message.success(`文章[${resp.title}]更新成功`)

      // 使用返回的数据再次绑定form表单
      form.title = resp.title
      form.content = resp.content
    } else {
      // 执行创建
      const resp = await BLOG_CREATE(form)
      Message.success(`文章[${resp.title}]创建成功`)
      router.push({ name: 'BackendBlogList' })
    }
  } catch (error) {
    Message.error(`保存失败: ${error}`)
  }
}

onMounted(async () => {
  try {
    const id = route.query.id
    if (id) {
      const resp = await BLOG_GET(route.query.id)
      // 绑定到form上面
      form.title = resp.title
      form.content = resp.content
    }
  } catch (error) {
    Message.error(`查询博客失败: ${error}`)
  }
})
</script>
<style scoped></style>
